#!/home/python/.virtualenvs/open/bin/python

import sys
sys.path.append('./')
sys.path.insert(0, "../")

import os
if not os.getenv('DJANGO_SETTINGS_MODULE'):
    os.environ['DJANGO_SETTINGS_MODULE'] = 'equity_mall.settings.prod'

import django
django.setup()


from celery import shared_task
import datetime, requests, json, logging
from django.conf import settings
from random import randint
from django.db import transaction

from equity_mall.utils.utils import get_sign_SM3, random_str
from orders.models import OrderInfo
from vouchers.models import *
from customers.utils import AlipayOpen, pay_transactions_jsapi, pay_transactions_native, favor_distributed_coupons, favor_query_coupons, favor_meituan_coupons, favor_query_coupons_sichun, favor_distributed_coupons_sichun
from activities.models import Channel
from alipaynfc.models import *
from alipaynfc.utils import check_merchant_nfc_trade
from cashbonus.models import CashActivity, CashActivityData

mobile_bank_logger = logging.getLogger('mobile_bank')


@shared_task
def mobile_bank_vouchers_update(data):
    openId = data['openId']
    couponId = data['couponId']
    stockId = data['stockId']
    status = data['status']
    datetime_now = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
    data_dict = {
        'channelType': 'wyh',
        "reqTraceId": datetime_now,
        "reqDate": datetime_now,
        "supplierId": "wyh",
        'stockId': stockId,
        'openId': openId,
        'status': status,
        'operateTime': datetime_now,
        'couponId': couponId
    }
    key = 'e114064e3a18bc94a2912759b13a001a'
    url = 'http://ydsq.91betterwei.com:9999/openplatform/wyhActivity/wyhCouponStatusUpdate'
    headers = {'Content-Type': 'application/json'}
    sign = get_sign_SM3(data_dict, key)
    data_dict['sign'] = sign
    response = requests.post(url=url, data=json.dumps(data_dict), headers=headers)
    mobile_bank_logger.info(f'{json.dumps(data_dict)},{response.json()}')
    return '手机银行优惠券推送完成'


@shared_task
def cancel_over_time_order(data):
    '''超时未支付订单'''
    order_id = data['order_id']
    instance = OrderInfo.objects.get(id=order_id)
    if instance.state == 1:
        ordergoods_set = instance.ordergoods_set.all()
        for ordergoods in ordergoods_set:
            goods = ordergoods.goods
            launched_goods = ordergoods.launched_goods
            count = ordergoods.count
            origin_sales = goods.sales
            origin_remain_stock = goods.remain_stock
            new_sales = origin_sales - count
            new_remain_stock = origin_remain_stock + count
            goods.sales = new_sales
            goods.remain_stock = new_remain_stock
            goods.save()
            if launched_goods:
                launched_origin_stock = launched_goods.stock
                launched_origin_sales = launched_goods.sales
                launched_new_stock = launched_origin_stock + count
                launched_new_sales = launched_origin_sales - count
                launched_goods.stock = launched_new_stock
                launched_goods.sales = launched_new_sales
                launched_goods.save()
            else:
                origin_stock = goods.stock
                new_stock = origin_stock + count
                goods.stock = new_stock
                goods.save()
        instance.state = 13
        instance.cancel_time = datetime.datetime.now()
        instance.total_point = 0
        instance.save()
        alidiscounponinfo_set = instance.alidiscountcouponinfo_set.all().filter(status=8).update(status=1)
    return '取消超时订单成功'


@shared_task
def distribute_couponbag(data):
    '''派发券包'''
    filp_id = data['filp_id']
    instance = CustomizeActivityFlipCARDS.objects.get(id=filp_id)
    customizeactivity = instance.customizeactivity
    customizeactivityrules_set = customizeactivity.customizeactivityrules_set.all()
    user = instance.customeruservice
    today = datetime.datetime.now()
    if instance.open_status == 2:
        for customizeactivityrules in customizeactivityrules_set:
            alidiscountcoupon = customizeactivityrules.alidiscountcoupon
            for i in range(customizeactivityrules.count):
                if alidiscountcoupon.coupon_channel == 1:
                    pass
                elif alidiscountcoupon.coupon_channel == 2:
                    out_biz_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}'
                    appid = settings.CUSTOMER_APP_ID_WYH
                    openid = user.wyh_openid
                    if alidiscountcoupon.platform_id == 13:
                        distribute_channel = Channel.objects.get(id=13)
                    else:
                        distribute_channel = Channel.objects.get(id=9)
                    data_json = {
                        "stock_id": alidiscountcoupon.template_id,
                        "out_request_no": out_biz_no,
                        "appid": appid,
                        "stock_creator_mchid": alidiscountcoupon.platform.mchid
                    }
                    data_dict = favor_distributed_coupons_sichun(data_json, openid, distribute_channel)
                    if 'code' in data_dict:
                        defaults = {
                            'alidiscountcoupon_id': alidiscountcoupon.id,
                            'user_id': openid,
                            'template_id': alidiscountcoupon.template_id,
                            'gmt_create': today,
                            'name': alidiscountcoupon.activity_name,
                            'out_biz_no': out_biz_no,
                            'customeruservice_id': user.id,
                            'companyuser_id': instance.companyuser_id,
                            'gmt_distributed': instance.open_time,
                            'level_id': instance.companyuser.level_id,
                            'mobile': user.mobile,
                            'coupon_channel': alidiscountcoupon.coupon_channel,
                            'status': 14,
                            'return_msg': data_dict['message'],
                            'appid': appid
                        }
                        voucherinfo = AliDiscountCouponInfo.objects.create(**defaults)
                    else:
                        while True:
                            activity_id = alidiscountcoupon.id
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count + 1
                            activity_new_remain_number = activity_origin_remain_number - 1
                            result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(send_count=activity_new_send_count, remain_number=activity_new_remain_number)
                            if result == 0:
                                continue
                            break
                        coupon_id = data_dict['coupon_id']
                        result = favor_query_coupons_sichun(coupon_id, openid, appid, distribute_channel)
                        defaults = {
                            'alidiscountcoupon_id': alidiscountcoupon.id,
                            'voucher_id': coupon_id,
                            'user_id': openid,
                            'template_id': result['stock_id'],
                            'gmt_active': result['available_begin_time'].replace('T', ' ').replace('+08:00', ''),
                            'gmt_expired': result['available_end_time'].replace('T', ' ').replace('+08:00', ''),
                            'total_amount': result['normal_coupon_information']['coupon_amount'] / 100,
                            'gmt_create': today,
                            'available_amount': result['normal_coupon_information']['coupon_amount'] / 100,
                            'name': result['coupon_name'],
                            'out_biz_no': out_biz_no,
                            'customeruservice_id': user.id,
                            'companyuser_id': instance.companyuser_id,
                            'gmt_distributed': instance.open_time,
                            'level_id': instance.companyuser.level_id,
                            'mobile': user.mobile,
                            'coupon_channel': alidiscountcoupon.coupon_channel,
                            'appid': appid
                        }
                        if today < datetime.datetime.strptime(defaults['gmt_active'], "%Y-%m-%d %H:%M:%S"):
                            defaults['status'] = 11
                        voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=defaults, voucher_id=coupon_id)
                    datail_data = {}
                    datail_data['flipcard_id'] = instance.id
                    datail_data['alidiscountcouponinfo_id'] = voucherinfo.id
                    CustomizeActivityFlipCARDSDetail.objects.get_or_create(defaults=datail_data, flipcard_id=instance.id, alidiscountcouponinfo_id=voucherinfo.id)
                elif alidiscountcoupon.coupon_channel == 5:
                    out_biz_no = f'{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}'
                    appid = settings.CUSTOMER_APP_ID_WYH
                    openid = user.wyh_openid
                    meituan_result = favor_meituan_coupons(out_biz_no, alidiscountcoupon.template_id, user.mobile)
                    if meituan_result['status'] != 'success':
                        defaults = {
                            'alidiscountcoupon_id': alidiscountcoupon.id,
                            'user_id': openid,
                            'template_id': alidiscountcoupon.template_id,
                            'gmt_create': today,
                            'name': alidiscountcoupon.activity_name,
                            'out_biz_no': out_biz_no,
                            'customeruservice_id': user.id,
                            'companyuser_id': instance.companyuser_id,
                            'gmt_distributed': instance.open_time,
                            'level_id': instance.companyuser.level_id,
                            'mobile': user.mobile,
                            'coupon_channel': alidiscountcoupon.coupon_channel,
                            'status': 14,
                            'return_msg': meituan_result['errorMsg'],
                            'appid': appid
                        }
                        voucherinfo = AliDiscountCouponInfo.objects.create(**defaults)
                    else:
                        while True:
                            activity_id = alidiscountcoupon.id
                            activity = AliDiscountCoupon.objects.get(id=activity_id)
                            activity_origin_send_count = activity.send_count
                            activity_origin_remain_number = activity.remain_number
                            activity_new_send_count = activity_origin_send_count + 1
                            activity_new_remain_number = activity_origin_remain_number - 1
                            result = AliDiscountCoupon.objects.filter(id=activity_id, send_count=activity_origin_send_count).update(send_count=activity_new_send_count, remain_number=activity_new_remain_number)
                            if result == 0:
                                continue
                            break
                        coupon_id = meituan_result['data'][0]['code']
                        gmt_create = datetime.datetime.now()
                        alidiscountcouponchannelcommonvoucher = activity.alidiscountcouponchannelcommonvoucher
                        if alidiscountcouponchannelcommonvoucher.usetime_type == 2:
                            gmt_expired = alidiscountcouponchannelcommonvoucher.end_fixed_time
                            gmt_active = alidiscountcouponchannelcommonvoucher.start_fixed_time
                        elif alidiscountcouponchannelcommonvoucher.usetime_type == 3:
                            gmt_expired = gmt_create + datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)
                            gmt_active = gmt_create
                        else:
                            gmt_active = (gmt_create + datetime.timedelta(days=1)).strftime("%Y-%m-%d 00:00:00")
                            gmt_expired =(gmt_create+ datetime.timedelta(days=alidiscountcouponchannelcommonvoucher.invalid_day)).strftime("%Y-%m-%d 23:59:59")
                        defaults = {
                            'alidiscountcoupon_id': alidiscountcoupon.id,
                            'voucher_id': coupon_id,
                            'user_id': openid,
                            'template_id': alidiscountcoupon.template_id,
                            'gmt_active': gmt_active,
                            'gmt_expired': gmt_expired,
                            'total_amount': alidiscountcoupon.amount,
                            'gmt_create': today,
                            'available_amount': alidiscountcoupon.amount,
                            'name': alidiscountcoupon.activity_name,
                            'out_biz_no': out_biz_no,
                            'customeruservice_id': user.id,
                            'companyuser_id': instance.companyuser_id,
                            'gmt_distributed': instance.open_time,
                            'level_id': instance.companyuser.level_id,
                            'mobile': user.mobile,
                            'coupon_channel': alidiscountcoupon.coupon_channel,
                            'appid': appid
                        }
                        if today < datetime.datetime.strptime(defaults['gmt_active'], "%Y-%m-%d %H:%M:%S"):
                            defaults['status'] = 11
                        voucherinfo, create = AliDiscountCouponInfo.objects.get_or_create(defaults=defaults, voucher_id=coupon_id)
                    datail_data = {}
                    datail_data['flipcard_id'] = instance.id
                    datail_data['alidiscountcouponinfo_id'] = voucherinfo.id
                    CustomizeActivityFlipCARDSDetail.objects.get_or_create(defaults=datail_data, flipcard_id=instance.id, alidiscountcouponinfo_id=voucherinfo.id)
                else:
                    pass
        instance.open_status = 4
        instance.save()


@shared_task
def cancel_over_time_nfc_quest(data):
    schedule_id = data['schedule_id']
    schedule = NFCDeviceBountyQuestSchedule.objects.get(id=schedule_id)
    quest = schedule.quest
    if schedule.quest_status == 1:
        business_no = quest.merchant.wyfMerchantID
        create_time = schedule.create_time.strftime("%Y-%m-%d %H:%M:%S")
        expired_time = schedule.expired_time.strftime("%Y-%m-%d %H:%M:%S")
        result = check_merchant_nfc_trade(business_no, create_time, expired_time)
        if result == 0:
            schedule.quest_status = 4
            schedule.cancel_time = datetime.datetime.now()
            schedule.save()
            quest.quest_status = 0
            quest.save()
            return '取消赏金任务成功'
        else:
            activity = CashActivity.objects.get(id=1028)
            amount = quest.amount
            date_now = datetime.datetime.now()
            with transaction.atomic():
                save_id = transaction.savepoint()
                try:
                    activity_id = activity.id
                    while True:
                        activity = CashActivity.objects.get(id=activity_id)
                        activity_origin_take_amount = activity.take_amount
                        activity_origin_remain_amount = activity.remain_amount
                        if activity_origin_remain_amount < amount:
                            transaction.savepoint_rollback(save_id)
                            return '活动已达到派发上限'
                        activity_new_take_amount = activity_origin_take_amount + amount
                        activity_new_remain_amount = activity_origin_remain_amount - amount
                        result = CashActivity.objects.filter(take_amount=activity_origin_take_amount, remain_amount=activity_origin_remain_amount, id=activity_id).update(take_amount=activity_new_take_amount, remain_amount=activity_new_remain_amount)
                        if result == 0:
                            continue
                        break
                    activity_data = {}
                    activity_data['amount'] = amount
                    activity_data['create_time'] = date_now
                    activity_data['cash_activity_id'] = activity.id
                    activity_data['state'] = 1
                    activity_data['customeruservice_id'] = schedule.customeruservice_id
                    identify = random_str()
                    nonce_str = random_str()
                    activity_data['identify'] = identify
                    activity_data['nonce_str'] = nonce_str
                    activity_data['desc'] = activity.name
                    activity_data['partner_trade_no'] = f'{date_now.strftime("%Y%m%d%H%M%S")}{"%06d" % randint(0, 999999)}{"%06d" % schedule.customeruservice_id}'
                    activity_data['expired_time'] = date_now + datetime.timedelta(hours=11)
                    activity_dat, create = CashActivityData.objects.get_or_create(defaults=activity_data, identify=identify)
                    schedule.award_id = activity_dat.id
                    schedule.quest_status = 2
                    schedule.success_time = date_now
                    schedule.save()
                    quest.quest_status = 2
                    quest.save()
                except:
                    transaction.savepoint_rollback(save_id)
                    return '系统繁忙,请刷新重试'
            transaction.savepoint_commit(save_id)
            return '完成任务'


if __name__ == '__main__':
    pass
    # mobile_bank_vouchers_update({"openId": "oXcKZwx5lSF3ZHZcpFRwZPxs33E4", "couponId": "50033240296", "stockId": "17894929", "status": "1"})
    # cancel_over_time_order({"order_id": 7623885})
    print(cancel_over_time_nfc_quest({"schedule_id": '15'}))